package pers.cz.mxgraph;

import org.dom4j.Element;

import java.util.*;

/**
 * @program: Reids
 * @description: MxCell
 * @author: Cheng Zhi
 * @create: 2023-01-06 10:18
 **/
public class MxCell extends MxElement {

    private static final String ATTR_ID = "id";

    private static final String ATTR_NAME = "value";

    private static final String START_VALUE = "start";

    private static final String START_KEY = "nodeName";

    private Map<String, Object> params;

    private MxGraphModel mxGraphModel;

    public MxCell(Element element) {
        super(element);
    }

    public MxCell(Element element, MxGraphModel mxGraphModel) {
        super(element);
        this.mxGraphModel = mxGraphModel;
    }

    public Integer getId() {
        return Integer.valueOf(getData().get(ATTR_ID));
    }

    public String getName() {

        return getData().get(ATTR_NAME);
    }

    public MxObject getMxObject() {

        return Optional.ofNullable(element.element("Object")).map(object -> new MxObject(object)).orElse(null);
    }

    public Map<String, String> getMxObjectData() {

        return Optional.ofNullable(getMxObject()).map(mxObject -> mxObject.getData()).orElse(new HashMap<>());
    }

    public Map<String, Object> getParams() {
        return params;
    }

    /**
     * 设置自定义参数，用于传递给下个节点
     * @param params
     */
    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    /**
     * 是否为开始节点
     * @return
     */
    public Boolean isStart() {

        String s = getMxObjectData().get(START_KEY);
        if (s != null && START_VALUE.equals(s)) {
            return true;
        }
        return false;
    }

    /**
     * 获取next节点，因为一个节点可能会有多个子节点
     * @return
     */
    public List<MxCell> getNextCell() {

        int currentId = getId();
        Integer nextId = 0;

        List<MxCell> list = new ArrayList<>();
        mxGraphModel.getMxEdges().stream().filter(mxEdge ->mxEdge.getSourceId() == currentId).forEach((p) -> {
            list.add(mxGraphModel.getMxCell(p.getTargetId()));
        });

        return list;
    }

    /**
     * 判断是否还有下个节点
     * @return
     */
    public boolean hasNext() {

        for (MxEdge mxEdge :mxGraphModel.getMxEdges()) {
            if (mxEdge.getSourceId() == getId()) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获取当前节点的所有上游节点的id
     * @return
     */
    public List<Integer> getUpstreamNode() {
        List<Integer> list = new ArrayList<>();
        for (MxEdge mxEdge :mxGraphModel.getMxEdges()) {
            if (mxEdge.getTargetId() == getId()) {
                list.add(mxEdge.getSourceId());
            }
        }

        return list;
    }

    /**
     * 判断当前节点是否有多个上游节点
     * @return
     */
    public boolean hasManyUpstreamMode() {
        if (getUpstreamNode().size() > 1) {
            return true;
        }

        return false;
    }

}
